<?php
class BaseController extends Controller {  
    public $layout = "layout.html";
	
    protected function isPost(){
        return $_SERVER['REQUEST_METHOD'] == 'POST';
    }
    
    protected function redirect( $url ) {
        header('location:' . $url);
        exit;
    }
    
    protected function alert($msg = null, $url = null){
        header("Content-type: text/html; charset=utf-8");
        $alert_msg = null === $msg ? '' : "alert('$msg');";
        if( empty($url) ) {
            $gourl = 'history.go(-1);';
        }else{
            $gourl = "window.location.href = '{$url}'";
        }
        echo "<script>$alert_msg $gourl</script>";
        exit;
    }
    
    protected function putjson($code, $data = null, $msg = '', $callback='callback'){
        header("Content-Type: application/x-javascript; charset=UTF-8");
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST');
        $json = json_encode(array('code'=>$code, 'data'=>$data, 'msg'=>$msg));
        if ( isset($GLOBALS['request_args'][$callback]) ) {
            exit(arg($callback). '('. $json . ')');
        } else {
            exit($json);
        }
    }
    
    public function arg($name = null, $default = null, $callback_funcname = null){
        $ret = parent::arg($name, $default, $callback_funcname);
        if( is_array($ret) ){
            array_walk($ret, function(&$v, $k){$v = trim(htmlspecialchars($v, ENT_QUOTES, 'UTF-8'));} );
        }else{
            $ret = trim(htmlspecialchars($ret, ENT_QUOTES, 'UTF-8'));
        }
        return $ret;
    }
    
    public function jsonOutput($data, $callback='callback'){
        $fun = htmlentities($this->arg($callback));
        $json = json_encode($data);
        echo empty($fun)? $json : "{$fun}({$json})";
        exit;
    }
    
    //全局控制缓存
    protected function setCacheAble(){
        $flag = arg('cache');
        if( 'no'==$flag ){
            define('CACHE_GET_ABLE', false);
            define('CACHE_SET_ABLE', false);
        }else if( 'update'==$flag ){
            define('CACHE_GET_ABLE', false);
            define('CACHE_SET_ABLE', true);
        }else{
            define('CACHE_GET_ABLE', true);
            define('CACHE_SET_ABLE', true);
        }
    }
    
    /**
     * 套用iframe，自由使用自己需要的样式，免受layout.html影响
     * 用法：放到action方法体内，需要输出页面的分支的第一行
     * 例如： 
     *      function actionXxx(){
     *          $this->iframe();
     *          ...
     *          ...
     *      }
     * @author biao
     * @since 2015-11-18
     */
    protected function iframe($route = ''){
        $this->route = $route ?: CONTROLLER_NAME . '/' . ACTION_NAME;//目标内容URL
        $this->request = arg();//转发参数
        if (1 == $_SERVER['HTTP_USE_IFRAME']) {
            $this->layout = null;//禁用外部布局
            return;
        } else {
            $this->display('iframe.html');
            exit;
        }
    }
    
} 